import os
from flask import Blueprint, request, render_template, jsonify, current_app
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize
from sqlalchemy import text  # 导入 text 函数
from flask_login import current_user
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import kami_web
from applications.schemas import kami_webOutSchema
from datetime import datetime

bp = Blueprint('kami', __name__, url_prefix='/kami')




#  网站基本设置-软件发布
@bp.get('/')
@authorize("system:kami:main")
def main():
    # db.create_all()

    return render_template('/system/kami/main.html')

#  查询数据
@bp.get('/table')
@authorize("system:kami:main")
def data():
    # site =kami_web.query.filter().all()
    # 查询参数构造
    mf = ModelFilter()
    kami = kami_web.query.filter(mf.get_filter(kami_web)).layui_paginate()
    count = kami.total
    data = data=model_to_dicts(schema=kami_webOutSchema, data=kami.items)

    # 更新data中的password字段内容替换为*
    for i in range(len(data)):
        data[i]['password'] = data[i]['password'][:4] + '*' * (len(data[i]['password'])-8) + data[i]['password'][-4:]
    return table_api(data=data, count=count)
    # 返回api
    # return table_api(data=model_to_dicts(schema=kami_webOutSchema, data=kami.items), count=count)
@bp.route('/query', methods=['POST','GET'])
@authorize("system:kami:main", log=True)
def query():
    
    if request.method == 'GET':
        selectname = request.args.get('selectname')
    if request.method == 'POST':
        data = request.get_json()
        selectname = data.get('selectname')
    # 查询参数构造
    mf = ModelFilter()
    if selectname == None or selectname =='':
        # 查询数据库表名称filename的filename字段及数据
        query = kami_web.query.filter(mf.get_filter(kami_web)).layui_paginate()
        count = query.total
    else:
        # 模糊查询数据库表中字段name、card、password、uid的数据包含selectname的结果
        query = kami_web.query.filter(mf.get_filter(kami_web)).filter(kami_web.name.like(f'%{selectname}%')|kami_web.card.like(f'%{selectname}%')|kami_web.password.like(f'%{selectname}%')|kami_web.uid.like(f'%{selectname}%')).layui_paginate()
        count = query.total
    
    data = model_to_dicts(schema=kami_webOutSchema, data=query.items)
    # print(data)
    # 返回api
    return table_api(msg="成功",data=data, count=count)

# 用户增加
@bp.get('/add')
@authorize("system:kami:add", log=True)
def add():
    return render_template('system/kami/add.html')

@bp.route('/save', methods=['post','get'])
@authorize("system:kami:add", log=True)
def save():
    data = request.get_json()
    # 将日期字符串转换为日期对象
    expire_time_str = data.get('expire_time')
    create_time_str = data.get('create_time')
    # 插入数据
    kami_data = kami_web(
        name = str_escape(data.get('name')),
        card = str_escape(data.get('card')),
        password = str_escape(data.get('password')),
        uid = str_escape(data.get('uid')),
        status = str_escape(data.get('status')),
        expire_time = datetime.strptime(expire_time_str, '%Y-%m-%d').date(),
        create_time = datetime.strptime(create_time_str, '%Y-%m-%d').date(),
        
    )
    # res_web = kami_web.query.filter_by(filename=str_escape(data.get('name'))).first()
    # if res_web: return fail_api(msg="该参数已存在")
    try:
        db.session.add(kami_data)
        db.session.commit()
        return success_api(msg="增加成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return fail_api(msg=f"增加失败")

#  编辑参数
@bp.route('/edit', methods=['post','get'])
@authorize("system:kami:edit", log=True)
def edit():
    id = request.args.get('id')
    kamidata = kami_web.query.filter_by(id=id).first()
    # 修改upload_time的数据为datetime对象
    kamidata.expire_time = kamidata.expire_time.strftime('%Y-%m-%d')
    kamidata.create_time = kamidata.create_time.strftime('%Y-%m-%d')
    return render_template('system/kami/edit.html', kami=kamidata)

#  编辑用户
@bp.route('/update', methods=['post','get'])
@authorize("system:kami:edit", log=True)
def update():
    data = request.get_json()
    id = data.get('id')
    # 将日期字符串转换为日期对象
    expire_time_str = data.get('expire_time')
    data['expire_time'] = datetime.strptime(expire_time_str, '%Y-%m-%d').date()
    create_time_str = data.get('create_time')
    data['create_time'] = datetime.strptime(create_time_str, '%Y-%m-%d').date()
    res = kami_web.query.filter_by(id=id).update(data)
    if not res: 
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")
    


#    参数删除
# @bp.route('/remove/<int:id>', methods=['DELETE'])
@bp.route('/remove', methods=['post'])
@authorize("system:kami:remove", log=True)
def delete():
    id = request.form.get('id')
    res = kami_web.query.filter_by(id=id).delete()
    if not res:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")

# 批量删除
@bp.route('/batchRemove', methods=['post'])
@authorize("system:kami:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = kami_web.query.filter_by(id=id).delete()
        if not res:
            return fail_api(msg="批量删除失败")
    db.session.commit()
    return success_api(msg="批量删除成功")